//
//  ZBLargeImageBrowserView.m
//  XZBProduct
//
//  Created by xzb on 2019/1/21.
//  Copyright © 2019 xzb. All rights reserved.
//

#import "ZBLargeImageBrowserView.h"
#import <ZBFancyCollectionView/UICollectionView+ZBFancy.h>
#import "ZBLargeImageBrowserViewCell.h"
#import "UIImage+YYAdd.h"
#import "ZBNetworkManager.h"

@interface ZBLargeImageBrowserView ()

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSURL *imageURL;
@property (nonatomic, strong) NSArray *cellModels;

@end

@implementation ZBLargeImageBrowserView

- (instancetype)init
{
    self = [super init];
    if (self) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.collectionView = [UICollectionView collectionViewWithLayout:layout];
        
        self.collectionView.backgroundColor = [UIColor blackColor];
        [self addSubview:self.collectionView];
        [self.collectionView zb_configTableView:^(ZBCollectionProtoFactory *config) {
            config.cell(@"<image>").cls(@"ZBLargeImageBrowserViewCell");
        }];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.collectionView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
}

- (void)loadLargeImageWithUrl:(NSString *)url
{
    self.imageURL = [NSURL URLWithString:url];
    
    [self handleImageURL];
}


- (void)handleImageURL
{
    NSString *fileName = [self.imageURL lastPathComponent];
    NSString *toPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [toPath stringByAppendingPathComponent:fileName];
    @weakify(self);
    NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedAlways  error:nil];
    if (!data) {
        [[ZBNetworkManager instance] downloadFileWithUrl:self.imageURL.absoluteString dirPath:toPath filename:fileName onComplete:^(ZBDownLoadRespModel *respModel) {
            if (!respModel.error) {
                @strongify(self);
                [self handleImageURL];
            } else {
                NSLog(@"download error");
            }
        } onProgress:nil];
        return;
    }
    
    UIImage *image = [UIImage imageWithData:data];
    
    if (CGSizeEqualToSize(image.size, CGSizeZero)) {
        NSLog(@"image size error");
        return;
    }
    
    CGFloat imageCount = image.size.width / CGRectGetWidth([UIScreen mainScreen].bounds);
    
    NSMutableArray *cellModels = [[NSMutableArray alloc] initWithCapacity:imageCount];
    
    @autoreleasepool {
        for (NSInteger imageIdx = 0; imageIdx < imageCount; imageIdx ++ ) {
            ZBLargeImageBrowserViewCellModel *cellModel = [ZBLargeImageBrowserViewCellModel cellModel];
            cellModel.cellHeight = CGRectGetWidth([UIScreen mainScreen].bounds);
            CGImageRef imageRef = image.CGImage;
            CGRect rect = CGRectMake(CGRectGetWidth([UIScreen mainScreen].bounds) * imageIdx , 0, CGRectGetWidth([UIScreen mainScreen].bounds),image.size.height);
            
            CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
            UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];
            cellModel.image = imageRect;
            CGImageRelease(imageRefRect);
            [cellModels addObject:cellModel];
        }
    }
    
    [self.collectionView zb_setup:^(ZBCollectionMaker *maker) {
        maker.section(@"<section-one>");
        for (ZBLargeImageBrowserViewCellModel *cellModel in cellModels) {
            maker.row(@"<image>").model(cellModel);
        }
    }];
    self.cellModels = [cellModels copy];
}

- (void)zb_event:(NSString *)event params:(NSDictionary *)params
{
    if ([event isEqualToString:@"ZBLargeImageBrowserView"]) {
        CGFloat y = [params zb_safeFloatValueForKey:@"contentOffsetY" defaultValue:0];
        ZBLargeImageBrowserViewCell *currentCell = (ZBLargeImageBrowserViewCell *)params[@"cell"];
        
        for (ZBLargeImageBrowserViewCell *cell in [self.collectionView visibleCells]) {
            if (cell != currentCell) {
                cell.contentScrollView.contentOffset = CGPointMake(0, y);
            }
            for (ZBLargeImageBrowserViewCellModel *cellModel in self.cellModels) {
                cellModel.contentOffsetY = y;
            }
        }
    }
}
@end
